import { defineConfig, Plugin } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'

// 简易开发期后端代理（仅在 dev 启用），用于调用百度 AI，避免前端直连产生 CORS 与密钥泄露
// 注意：生产环境请迁移到真实后端服务
function baiduProxyPlugin(): Plugin {
  // 这些密钥仅用于本地开发，正式环境严禁放到前端
  const API_KEY = 'o9YfS0IY3NJtTvQbueFuArgE'
  const SECRET_KEY = 'Et9A7AANQnOWqftooZTxPuGNmUhEW9up'
  const GROUP_ID = 'user'

  let cachedToken: string | null = null
  let tokenExpireAt = 0

  const getAccessToken = async () => {
    const now = Date.now()
    if (cachedToken && now < tokenExpireAt) return cachedToken

    const params = new URLSearchParams()
    params.set('grant_type', 'client_credentials')
    params.set('client_id', API_KEY)
    params.set('client_secret', SECRET_KEY)

    const resp = await fetch('https://aip.baidubce.com/oauth/2.0/token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: params.toString(),
    })
    const data = await resp.json() as any
    if (!resp.ok || (data && data.error)) {
      throw new Error(data?.error_description || `获取访问令牌失败（HTTP ${resp.status}）`)
    }
    cachedToken = data.access_token
    tokenExpireAt = Date.now() + (data.expires_in ? data.expires_in * 1000 : 0) - 60_000
    return cachedToken!
  }

  return {
    name: 'dev-baidu-proxy',
    configureServer(server) {
      server.middlewares.use(async (req, res, next) => {
        if (!req.url) return next()
        const handleJsonBody = async () => {
          const chunks: Buffer[] = []
          await new Promise<void>((resolve) => {
            req.on('data', (c) => chunks.push(c))
            req.on('end', () => resolve())
          })
          const raw = Buffer.concat(chunks).toString('utf-8')
          return raw ? JSON.parse(raw) : {}
        }

        // 人脸搜索（已存在）
        if (req.method === 'POST' && req.url.startsWith('/api/baidu/face/search')) {
          try {
            const body = await handleJsonBody()
            const { image, liveness_control = 'HIGH', quality_control = 'NORMAL', match_threshold = 80 } = body || {}
            if (!image) {
              res.statusCode = 400
              res.end(JSON.stringify({ code: 400, msg: '缺少参数：image（base64）' }))
              return
            }

            const token = await getAccessToken()
            const apiUrl = `https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=${encodeURIComponent(token)}`
            const baiduResp = await fetch(apiUrl, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                image,
                image_type: 'BASE64',
                group_id_list: GROUP_ID,
                liveness_control,
                quality_control,
                max_user_num: 1,
                match_threshold,
              }),
            })
            const result = await baiduResp.json() as any
            res.setHeader('Content-Type', 'application/json')
            res.end(JSON.stringify({ code: 200, data: result }))
          } catch (err) {
            res.statusCode = 500
            res.end(JSON.stringify({ code: 500, msg: '服务器内部错误' }))
          }
          return
        }

        // 获取组内用户列表
        if (req.method === 'POST' && req.url.startsWith('/api/baidu/face/group/getusers')) {
          try {
            const body = await handleJsonBody()
            const { start = 0, length = 100 } = body || {}
            const token = await getAccessToken()
            const apiUrl = `https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getusers?access_token=${encodeURIComponent(token)}`
            const baiduResp = await fetch(apiUrl, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ group_id: GROUP_ID, start, length })
            })
            const result = await baiduResp.json() as any
            res.setHeader('Content-Type', 'application/json')
            res.end(JSON.stringify({ code: 200, data: result }))
          } catch (err) {
            res.statusCode = 500
            res.end(JSON.stringify({ code: 500, msg: '服务器内部错误' }))
          }
          return
        }

        // 获取用户信息（含 face_list）
        if (req.method === 'POST' && req.url.startsWith('/api/baidu/face/user/get')) {
          try {
            const body = await handleJsonBody()
            const { user_id } = body || {}
            if (!user_id) { res.statusCode = 400; res.end(JSON.stringify({ code: 400, msg: '缺少参数：user_id' })); return }
            const token = await getAccessToken()
            const apiUrl = `https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/get?access_token=${encodeURIComponent(token)}`
            const baiduResp = await fetch(apiUrl, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ group_id: GROUP_ID, user_id })
            })
            const result = await baiduResp.json() as any
            res.setHeader('Content-Type', 'application/json')
            res.end(JSON.stringify({ code: 200, data: result }))
          } catch (err) {
            res.statusCode = 500
            res.end(JSON.stringify({ code: 500, msg: '服务器内部错误' }))
          }
          return
        }

        // 获取用户的人脸列表（官方建议接口）
        if (req.method === 'POST' && req.url.startsWith('/api/baidu/face/face/getlist')) {
          try {
            const body = await handleJsonBody()
            const { user_id, start = 0, length = 100 } = body || {}
            if (!user_id) { res.statusCode = 400; res.end(JSON.stringify({ code: 400, msg: '缺少参数：user_id' })); return }
            const token = await getAccessToken()
            const apiUrl = `https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/getlist?access_token=${encodeURIComponent(token)}`
            const baiduResp = await fetch(apiUrl, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ group_id: GROUP_ID, user_id, start, length })
            })
            const result = await baiduResp.json() as any
            res.setHeader('Content-Type', 'application/json')
            res.end(JSON.stringify({ code: 200, data: result }))
          } catch (err) {
            res.statusCode = 500
            res.end(JSON.stringify({ code: 500, msg: '服务器内部错误' }))
          }
          return
        }

        // 添加人脸
        if (req.method === 'POST' && req.url.startsWith('/api/baidu/face/user/add')) {
          try {
            const body = await handleJsonBody()
            const { image, user_id, user_info = '', action_type = 'APPEND' } = body || {}
            if (!image || !user_id) { res.statusCode = 400; res.end(JSON.stringify({ code: 400, msg: '缺少参数：image 或 user_id' })); return }
            const token = await getAccessToken()
            const apiUrl = `https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=${encodeURIComponent(token)}`
            const baiduResp = await fetch(apiUrl, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ image, image_type: 'BASE64', group_id: GROUP_ID, user_id, user_info, action_type })
            })
            const result = await baiduResp.json() as any
            res.setHeader('Content-Type', 'application/json')
            res.end(JSON.stringify({ code: 200, data: result }))
          } catch (err) {
            res.statusCode = 500
            res.end(JSON.stringify({ code: 500, msg: '服务器内部错误' }))
          }
          return
        }

        // 删除某张人脸
        if (req.method === 'POST' && req.url.startsWith('/api/baidu/face/face/delete')) {
          try {
            const body = await handleJsonBody()
            const { user_id, face_token } = body || {}
            if (!user_id || !face_token) { res.statusCode = 400; res.end(JSON.stringify({ code: 400, msg: '缺少参数：user_id 或 face_token' })); return }
            const token = await getAccessToken()
            const apiUrl = `https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/delete?access_token=${encodeURIComponent(token)}`
            const baiduResp = await fetch(apiUrl, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ group_id: GROUP_ID, user_id, face_token })
            })
            const result = await baiduResp.json() as any
            res.setHeader('Content-Type', 'application/json')
            res.end(JSON.stringify({ code: 200, data: result }))
          } catch (err) {
            res.statusCode = 500
            res.end(JSON.stringify({ code: 500, msg: '服务器内部错误' }))
          }
          return
        }
        next()
      })
    },
  }
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [react(), tailwindcss(), baiduProxyPlugin()],
})
